﻿/*
 * Copyright (c) 2011 Roberto García López
 * 
 * email: vcrobe@gmail.com
 * 
 * website: http://vcrobe.blogspot.com
 * 
 * project host: http://vectorGraphics.codeplex.com
 * 
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.Windows;
using SlimDX.Direct3D9;
using SlimDX;
using System.Drawing;

namespace Ellipse
{
	static class Program
	{
		static RenderForm form;
		static Device device;

		#region Helpers

		static void SetupDevice()
		{
			form = new RenderForm("Ellipse algorithm with texture demonstration");
			form.Width = form.Height = 400;
			// Prepare the device (graphic card)
			device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing,
				new PresentParameters()
				{
					BackBufferWidth = form.ClientSize.Width,
					BackBufferHeight = form.ClientSize.Height
				}
			);
		}

		static void SetupProjection()
		{
			const int projSize = 5;
			Matrix proj = Matrix.OrthoOffCenterRH(-projSize, projSize, -projSize, projSize, 0, 1);
			device.SetTransform(TransformState.Projection, proj);
		}

		#endregion

		[STAThread]
		static void Main()
		{
			// Create the ellipse
			PolygonData pd = Splines.CreateEllipse(5, 5, 1, true);
			// Get the vertex buffer's size
			int bufferSize = 20 * (pd.vertices.Count + 1);

			SetupDevice();
			SetupProjection();
			device.SetRenderState(RenderState.CullMode, Cull.Clockwise);
			device.SetRenderState(RenderState.Lighting, false);
			// Create the texture
			Texture texture = Texture.FromFile(device, "Textures/nature.jpg");

			// Create a new vertex buffer
			VertexBuffer vertices = new VertexBuffer(device, bufferSize, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
			try
			{
				// Lock the buffer and get a pointer to it
				DataStream ds = vertices.Lock(0, 0 /*lock the entire buffer*/, LockFlags.None);
				// Write the vertices to the buffer
				WriteDataToStream(ds, pd);
			}
			finally
			{
				// Finish the write operation in the buffer
				vertices.Unlock();
			}

			// Define the vertex data layout
			VertexElement[] vertexElems = new[] {
        		new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
				new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
				VertexElement.VertexDeclarationEnd
        	};

			VertexDeclaration vertexDecl = new VertexDeclaration(device, vertexElems);

			MessagePump.Run(form, () =>
			{
				device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkGray, 1, 0);

				device.BeginScene();
					device.SetStreamSource(0, vertices, 0, 20);
					device.VertexDeclaration = vertexDecl;
					device.SetTexture(0, texture);
					device.DrawPrimitives(PrimitiveType.TriangleFan, 0, pd.vertices.Count - 2);
				device.EndScene();

				device.Present();
			});

			foreach (var item in ObjectTable.Objects)
				item.Dispose();
		}

		private static void WriteDataToStream(DataStream ds, PolygonData pd)
		{
			for (int i = 0; i < pd.vertices.Count; i++)
			{
				ds.Write(new Vertex() { Position = pd.vertices[i], tu = pd.textureCoordinates[i].X, tv = pd.textureCoordinates[i].Y });
			}
			// Write the first vertex as the last to close the polygon
			ds.Write(new Vertex() { Position = pd.vertices[0], tu = pd.textureCoordinates[0].X, tv = pd.textureCoordinates[0].Y });
		}
	}
}
